//
//  PopoverAnimator.m
//  Weibo
//
//  Created by Justsoso on 16/4/26.
//  Copyright © 2016年 Justsoso. All rights reserved.
//

#import "PopoverAnimator.h"
#import "PopoverViewController.h"
#import "PopoverPresentationController.h"

@interface PopoverAnimator()
{
    BOOL isPresent; // 是否弹出
}

@end
@implementation PopoverAnimator

#pragma mark - UIViewControllerTransitioningDelegate

// 告诉系统谁来负责转场动画
- (nullable UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source
{
    PopoverPresentationController *pc = [[PopoverPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
    pc.presentFrame = self.presentFrame;
    return pc;
}

// 谁来负责自定义弹出动画
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    isPresent = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:kNontificationPopoverWillShow object:nil userInfo:nil];
    return self;
}

// 谁来负责自定义消失动画
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    isPresent = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:kNontificationPopoverWillDismiss object:nil userInfo:nil];
    return self;
}

#pragma mark - 自定义动画效果

// 动画的时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    return 0.5;
}
// This method can only  be a nop if the transition is interactive and not a percentDriven interactive transition.
// 具体动画怎么进行
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    if(isPresent)
    {
        NSLog(@"展现");
        // 展现出来
        // 1. 拿到要展现的视图
        UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
        toView.alpha = 0;
        // 将要展现的视图添加到容器上
        [[transitionContext containerView] addSubview:toView];
        
        // 2. 执行动画
        [UIView animateWithDuration:0.5 animations:^{
            // 重置
            toView.alpha = 1;
        }completion:^(BOOL finished) {
            // 告诉系统执行完了
            [transitionContext completeTransition:YES];
        }];
    }
    else
    {
        NSLog(@"关闭");
        // 关闭
        
        UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        fromView.transform = CGAffineTransformIdentity;
        
        
        [UIView animateWithDuration:1 animations:^{
            fromView.alpha = 0;
        }completion:^(BOOL finished) {
            // 告诉系统执行完了
            [transitionContext completeTransition:YES];
        }];
    }
}

@end
